package com.dongwu.config;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

import org.springframework.util.ResourceUtils;

import com.dongwu.common.constants.TencentIMConstants;
import com.tls.sigcheck.tls_sigcheck;
/**
 *  腾讯云通信IM生成Usig方法
 * @author xyj
 *
 */
public class tencentIMGetSig {

	public static String GetSig(String username) throws Exception {
		String jnipath = ""; // jni路径
		File priKeyFile = null; // 私钥
		File pubKeyFile = null; // 公钥
		tls_sigcheck demo = new tls_sigcheck();

		// 获取当前系统类型
		String os = System.getProperty("os.name");
		if (os.toLowerCase().startsWith("win")) {
			// windows下获取jnisigcheck.dll的绝对路径
			File jniFile = ResourceUtils.getFile("classpath:tencentIMkey/jnisigcheck.dll");
			jnipath = jniFile.getAbsolutePath();
			priKeyFile = ResourceUtils.getFile("classpath:tencentIMkey/ec_key.pem");
			pubKeyFile = ResourceUtils.getFile("classpath:tencentIMkey/public.pem");
			// jnipath =
			// jniFile.getAbsolutePath().replace("\\","\\\\");windows如果路径找不到则加上这段代码
		} else {
			// linux环境下则获取jnisigcheck.so
			// File jniFile =
			// ResourceUtils.getFile("classpath:tencentIMkey/jnisigcheck.so");
			// jnipath = jniFile.getAbsolutePath();
			jnipath = TencentIMConstants.JNIPATH;
			pubKeyFile = new File(TencentIMConstants.PUBKEYFILE);
			priKeyFile = new File(TencentIMConstants.PRIKEYFILE);
		}
		// 使用前请修改动态库的加载路径
		demo.loadJniLib(jnipath);

		StringBuilder strBuilder = new StringBuilder();
		String s = "";

		BufferedReader br = new BufferedReader(new FileReader(priKeyFile));
		while ((s = br.readLine()) != null) {
			strBuilder.append(s + '\n');
		}
		br.close();
		String priKey = strBuilder.toString();
		int ret = demo.tls_gen_signature_ex2(TencentIMConstants.SDKAPPID, username, priKey);

		if (0 != ret) {
			System.out.println("ret " + ret + " " + demo.getErrMsg());
		} else {
			System.out.println("sig:\n" + demo.getSig());
		}
		br = new BufferedReader(new FileReader(pubKeyFile));
		strBuilder.setLength(0);
		while ((s = br.readLine()) != null) {
			strBuilder.append(s + '\n');
		}
		br.close();
		String pubKey = strBuilder.toString();
		ret = demo.tls_check_signature_ex2(demo.getSig(), pubKey, username, TencentIMConstants.ACCOUNT_IDENTIFIER);
		if (0 != ret) {
			System.out.println("ret " + ret + " " + demo.getErrMsg());
		} else {
			System.out.println(
					"--\nverify ok -- expire time " + demo.getExpireTime() + " -- init time " + demo.getInitTime());
		}
		return demo.getSig();
	}
}
